package com.itsu.admin.service.impl;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.itsu.admin.service.NodeService;
import com.itsu.job.components.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jerry.Su
 * @Date 2022/2/9 16:18
 */
@Service
public class NodeServiceImpl implements NodeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Map<String, String>> getAllNodes() {
        String nodeStr = stringRedisTemplate.opsForValue().get(Const.REGISTER_RPC_NODES);
        return StrUtil.split(nodeStr, Const.RPC_NODE_SPLIT, true, true).stream().map(x -> {
            MapBuilder<String, String> builder = MapUtil.builder();
            String status = stringRedisTemplate.opsForValue().get(x);
            return builder.put("nodeAddress", x)
                    .put("status", status)
                    .build();
        }).collect(Collectors.toList());
    }

    @Override
    public String upNode(String nodeAddress) {
        String status = stringRedisTemplate.opsForValue().get(nodeAddress);
        if (Const.UP_STATUS.equals(status)) {
            return "current node is already be up status";
        }

        String nodeStr = stringRedisTemplate.opsForValue().get(Const.REGISTER_RPC_NODES);
        List<String> nodes = StrUtil.split(nodeStr, Const.RPC_NODE_SPLIT, true, true);
        for (String node : nodes) {
            if (node.equals(nodeAddress)) {
                stringRedisTemplate.opsForValue().set(nodeAddress, Const.UP_STATUS);
                break;
            }
        }
        return Const.UP_STATUS;
    }

    @Override
    public String downNode(String nodeAddress) {
        String status = stringRedisTemplate.opsForValue().get(nodeAddress);
        if (Const.DOWN_STATUS.equals(status)) {
            return "current node is already be down status";
        }

        String nodeStr = stringRedisTemplate.opsForValue().get(Const.REGISTER_RPC_NODES);
        List<String> nodes = StrUtil.split(nodeStr, Const.RPC_NODE_SPLIT, true, true);
        for (String node : nodes) {
            if (node.equals(nodeAddress)) {
                stringRedisTemplate.opsForValue().set(nodeAddress, Const.DOWN_STATUS);
                break;
            }
        }
        return Const.DOWN_STATUS;
    }
}
